import os
import uuid
import helpers.FileHelper as FileHelper
import script.LuaMerger as LuaMerger


class Feature:

    @staticmethod
    def from_path(path):
        conf_path = os.path.join(path, "content.json")
        if os.path.exists(conf_path):
            conf = FileHelper.r_json(conf_path)
            if "tag" in conf:
                return Feature(path, conf_path)

    def __init__(self, root_path, conf_path):
        self.root_path = root_path
        self.conf_path = conf_path

    def rehash(self, prefix=""):
        conf = FileHelper.r_json(self.conf_path)
        if "tag" not in conf:
            return False
        conf["tag"] = prefix + uuid.uuid1().hex
        FileHelper.w_json(conf, self.conf_path)
        return True

    def features(self):
        return [self]

    def merge_for_main(self):
        return LuaMerger.merge(os.path.join(self.root_path, "lua"), "src/MainEntry", "GraphSystem")

    def merge_for_seek(self):
        return LuaMerger.merge(os.path.join(self.root_path, "lua"), "src/SeekEntry", "SeekModeScript")

    def merge_for_anim(self):
        return LuaMerger.merge(os.path.join(self.root_path, "lua"), "src/AnimEntry", "SeekModeScript")

    def merge_for_text(self):
        return LuaMerger.merge(os.path.join(self.root_path, "lua"), "src/TextEntry", "TextAnim")

    def repair_sticker_images(self):
        conf = FileHelper.r_json(os.path.join(self.root_path, "clip.json"))
        files = []
        for tex_name in conf["texturefiles"]:
            files.append(os.path.join(self.root_path, tex_name))
        entities = conf["parts"]
        for entity_name in entities:
            entity = entities[entity_name]
            for clip_name in entity:
                clip_conf = entity[clip_name]
                image_refs = clip_conf["textureIdx"]["idx"]
                for i, idx in enumerate(image_refs):
                    image_path = os.path.join(self.root_path, clip_name, "{}_{:0>3}.png".format(clip_name, i))
                    if not os.path.exists(image_path):
                        FileHelper.cp(files[image_refs[i]], image_path)

